package com.tulei.qqread;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static java.lang.Thread.sleep;


public class QQReadUtil {

    public static List<Book> getData(Integer page) {

        List<Book> bookList = new ArrayList<>();
        for (int i = 1; i <= page; i++) {

            Connection connect = Jsoup.connect("https://book.qq.com/book-rank/male-sell/cycle-5-" + i);
            Document document;
            try {
                document = connect.get();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            Elements elements = document.getElementsByClass("tabs-content");
            Elements elementBooks = elements.get(0).getElementsByClass("book-large rank-book");
            for (Element elementBook : elementBooks) {
                Book book = new Book();
                try {
                    String title = elementBook.select("h4").text();
                    book.setTitle(title);
                } catch (Exception e) {
                    book.setTitle("");
                    System.out.println("Error extracting title: " + e.getMessage());
                }

                try {
                    String intro = elementBook.select(".intro").text();
                    book.setIntro(intro.length() > 100 ? intro.substring(0, 100) : intro);
                } catch (Exception e) {
                    book.setIntro(""); // Set intro to an empty string in case of an exception
                    System.out.println("Error extracting intro: " + e.getMessage());
                }

                try {
                    String author = elementBook.select(".other a:first-child").text();
                    book.setAuthor(author);
                } catch (Exception e) {
                    book.setAuthor("");
                    System.out.println("Error extracting author: " + e.getMessage());
                }

                try {
                    String kind = elementBook.select(".other a:nth-child(2)").text().trim().replace("·", "");
                    book.setKind(kind);
                } catch (Exception e) {
                    book.setKind("N/A");
                    System.out.println("Error extracting kind: " + e.getMessage());
                }

                try {

                    String serial = elementBook.select(".other span").get(0).text().replace("·", "");
                    book.setSerial(serial);

                    String wordCount = elementBook.select(".other span:last-child").text().replace("·", "");
                    book.setCount(wordCount);
                } catch (Exception e) {
                    book.setSerial("N/A");
                    book.setCount("N/A");
                    System.out.println("Error extracting serial or word count: " + e.getMessage());
                }
                bookList.add(book);
            }
            System.out.println("第" +  i + "页保存成功............");
            try {
                sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        return bookList;

    }


    public static void saveExcel(List<Book> bookList) {
        Map<String, List<String>> kindBooksMap = new HashMap<>();
        for (Book book : bookList) {
            String kind = book.getKind();
            kindBooksMap.putIfAbsent(kind, new ArrayList<>());
            kindBooksMap.get(kind).add(book.getTitle());
        }

        // 创建Excel文件
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Book Kinds");

        // 设置标题行样式
        CellStyle headerStyle = workbook.createCellStyle();
        Font headerFont = workbook.createFont();
        headerFont.setBold(true);
        headerStyle.setFont(headerFont);
        headerStyle.setAlignment(HorizontalAlignment.CENTER);

        int rowNum = 0;
        Row headerRow = sheet.createRow(rowNum++);
        createCell(headerRow, 0, "Kind", headerStyle);
        createCell(headerRow, 1, "Count", headerStyle);
        createCell(headerRow, 2, "Books", headerStyle);

        // 填充数据
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setWrapText(true); // 自动换行
        for (Map.Entry<String, List<String>> entry : kindBooksMap.entrySet()) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(entry.getKey());
            row.createCell(1).setCellValue(entry.getValue().size());
            row.createCell(2).setCellValue(String.join(", ", entry.getValue()));
            row.getCell(2).setCellStyle(cellStyle);
        }

        // 自动调整列宽
        for (int i = 0; i < 3; i++) {
            sheet.autoSizeColumn(i);
        }

        // 写入Excel文件
        try (FileOutputStream fileOut = new FileOutputStream("BookKindStatistics.xlsx")) {
            workbook.write(fileOut);
            System.out.println("Excel file created successfully.");
        } catch (IOException e) {
            System.err.println("Failed to write Excel file: " + e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                workbook.close();
            } catch (IOException e) {
                System.err.println("Failed to close workbook: " + e.getMessage());
                e.printStackTrace();
            }
        }
    }

    private static void createCell(Row row, int column, String value, CellStyle style) {
        Cell cell = row.createCell(column);
        cell.setCellValue(value);
        cell.setCellStyle(style);
    }
}
